package com.gmadmin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gmadmin.entity.MessageInfo;
import com.gmadmin.entity.MessageNotice;
import com.gmadmin.entity.dto.MessageInfoDto;
import com.gmadmin.entity.vo.MessageInfoVo;
import com.gmadmin.entity.vo.MessageNoticeVo;
import com.gmadmin.exception.BaseException;
import com.gmadmin.mapper.MessageInfoMapper;
import com.gmadmin.mq.template.MessageNoticeTemplate;
import com.gmadmin.service.MessageInfoService;
import com.gmadmin.service.MessageNoticeService;
import com.gmadmin.utils.CollectionBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangliang
 * @version 1.0
 * @date 2022/8/3 1:20
 */
@Service
public class MessageInfoServiceImpl extends ServiceImpl<MessageInfoMapper, MessageInfo> implements MessageInfoService {


    private final MessageNoticeService noticeService;

    private final MessageNoticeTemplate noticeTemplate;

    public MessageInfoServiceImpl(MessageNoticeService noticeService, MessageNoticeTemplate noticeTemplate) {
        this.noticeService = noticeService;
        this.noticeTemplate = noticeTemplate;
    }

    @Override
    public List<MessageInfoVo> findInfoByMsgId(List<Long> msgIds) {
        List<MessageInfo> messageInfos = baseMapper.findInfoByMsgId(msgIds);
        return CollectionBeanUtils.copyListProperties(messageInfos, MessageInfoVo::new);
    }

    @Transactional(rollbackFor = BaseException.class)
    @Override
    public void saveMessageInfoAndNotify(MessageInfoDto infoDto) {
        MessageInfo messageInfo = new MessageInfo();
        BeanUtils.copyProperties(infoDto, messageInfo);
        baseMapper.insert(messageInfo);

        MessageInfoVo infoVo = new MessageInfoVo();
        BeanUtils.copyProperties(messageInfo, infoVo);
        if (messageInfo.getType() == 1) {
            List<MessageNotice> messageNotices = CollectionBeanUtils.copyListProperties(infoDto.getMessageNotice(), MessageNotice::new);
            messageNotices = messageNotices.stream().map(messageNotice -> {
                messageNotice.setMsgInfoId(messageInfo.getId());
                return messageNotice;
            }).collect(Collectors.toList());
            noticeService.saveBatch(messageNotices);
            infoVo.setMessageNotice(CollectionBeanUtils.copyListProperties(messageNotices, MessageNoticeVo::new));
        } else {
            throw new BaseException("当前类型消息系统暂不支持!!!");
        }
        noticeTemplate.syncSendMessageNotify(infoVo);
    }
}
